<template>
  <div class="classes-page">
    <div class="page-header">
      <h2 class="page-title">班级管理</h2>
      <el-button type="primary" @click="showAddDialog = true">
        <el-icon><Plus /></el-icon>
        添加班级
      </el-button>
    </div>

    <!-- 班级卡片列表 -->
    <div class="classes-grid">
      <el-card
        v-for="cls in appStore.classes"
        :key="cls.id"
        class="class-card"
        shadow="hover"
        @click="viewClassDetail(cls)"
      >
        <div class="class-header">
          <div class="class-icon">
            <el-icon><OfficeBuilding /></el-icon>
          </div>
          <div class="class-info">
            <h3 class="class-name">{{ cls.name }}</h3>
            <p class="class-grade">{{ cls.grade }}级</p>
          </div>
          <div class="class-actions" @click.stop>
            <el-dropdown trigger="click">
              <el-button type="text" size="small">
                <el-icon><MoreFilled /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="editClass(cls)">
                    <el-icon><Edit /></el-icon>
                    编辑
                  </el-dropdown-item>
                  <el-dropdown-item @click="deleteClass(cls)" divided>
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
        
        <div class="class-stats">
          <div class="stat-item">
            <div class="stat-number">{{ cls.student_count }}</div>
            <div class="stat-label">学生数量</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ getClassTeacherCount(cls) }}</div>
            <div class="stat-label">任课教师</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ getClassCourseCount(cls) }}</div>
            <div class="stat-label">开设课程</div>
          </div>
        </div>
        
        <div class="class-footer">
          <el-tag size="small" type="info">{{ cls.grade }}级</el-tag>
          <el-button type="primary" size="small" @click.stop="viewStudents(cls)">
            查看学生
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 添加/编辑班级对话框 -->
    <el-dialog
      :title="isEditing ? '编辑班级' : '添加班级'"
      v-model="showAddDialog"
      width="400px"
      @close="resetForm"
    >
      <el-form
        ref="classFormRef"
        :model="classForm"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="班级名称" prop="name">
          <el-input v-model="classForm.name" placeholder="请输入班级名称" />
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-select v-model="classForm.grade" placeholder="请选择年级">
            <el-option label="2021级" value="2021" />
            <el-option label="2022级" value="2022" />
            <el-option label="2023级" value="2023" />
            <el-option label="2024级" value="2024" />
          </el-select>
        </el-form-item>
        <el-form-item label="专业方向" prop="major">
          <el-input v-model="classForm.major" placeholder="请输入专业方向" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            {{ isEditing ? '更新' : '添加' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 班级详情对话框 -->
    <el-dialog
      title="班级详情"
      v-model="showDetailDialog"
      width="600px"
    >
      <div v-if="selectedClass" class="class-detail">
        <div class="detail-header">
          <h3>{{ selectedClass.name }}</h3>
          <el-tag type="primary">{{ selectedClass.grade }}级</el-tag>
        </div>
        
        <el-descriptions :column="2" border>
          <el-descriptions-item label="班级名称">
            {{ selectedClass.name }}
          </el-descriptions-item>
          <el-descriptions-item label="年级">
            {{ selectedClass.grade }}级
          </el-descriptions-item>
          <el-descriptions-item label="学生数量">
            {{ selectedClass.student_count }}人
          </el-descriptions-item>
          <el-descriptions-item label="班主任">
            张老师
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            2023-09-01
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag type="success">正常</el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="class-courses">
          <h4>开设课程</h4>
          <el-tag
            v-for="course in appStore.courses.slice(0, 3)"
            :key="course.id"
            class="course-tag"
          >
            {{ course.name }}
          </el-tag>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAppStore } from '../stores/app'

const router = useRouter()
const appStore = useAppStore()

const showAddDialog = ref(false)
const showDetailDialog = ref(false)
const isEditing = ref(false)
const selectedClass = ref(null)
const classFormRef = ref()

// 班级表单数据
const classForm = reactive({
  id: null,
  name: '',
  grade: '',
  major: '',
  student_count: 0
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入班级名称', trigger: 'blur' }
  ],
  grade: [
    { required: true, message: '请选择年级', trigger: 'change' }
  ],
  major: [
    { required: true, message: '请输入专业方向', trigger: 'blur' }
  ]
}

// 方法
const getClassTeacherCount = (cls) => {
  return Math.floor(Math.random() * 5) + 3 // 模拟数据
}

const getClassCourseCount = (cls) => {
  return Math.floor(Math.random() * 3) + 5 // 模拟数据
}

const viewClassDetail = (cls) => {
  selectedClass.value = cls
  showDetailDialog.value = true
}

const viewStudents = (cls) => {
  router.push({
    path: '/students',
    query: { class: cls.name }
  })
}

const editClass = (cls) => {
  isEditing.value = true
  showAddDialog.value = true
  Object.assign(classForm, cls)
}

const deleteClass = async (cls) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除班级"${cls.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里应该调用API删除班级
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  try {
    await classFormRef.value.validate()
    
    if (isEditing.value) {
      // 更新班级
      const index = appStore.classes.findIndex(c => c.id === classForm.id)
      if (index !== -1) {
        Object.assign(appStore.classes[index], classForm)
      }
      ElMessage.success('更新成功')
    } else {
      // 添加班级
      const newClass = {
        ...classForm,
        id: Date.now(),
        student_count: 0
      }
      appStore.classes.push(newClass)
      ElMessage.success('添加成功')
    }
    
    showAddDialog.value = false
    resetForm()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(isEditing.value ? '更新失败' : '添加失败')
    }
  }
}

const resetForm = () => {
  isEditing.value = false
  Object.assign(classForm, {
    id: null,
    name: '',
    grade: '',
    major: '',
    student_count: 0
  })
  if (classFormRef.value) {
    classFormRef.value.resetFields()
  }
}

// 生命周期
onMounted(async () => {
  try {
    await Promise.all([
      appStore.fetchClasses(),
      appStore.fetchCourses()
    ])
  } catch (error) {
    ElMessage.error('加载数据失败')
  }
})
</script>

<style scoped>
.classes-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  color: #303133;
  font-weight: 500;
}

.classes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.class-card {
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.class-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.class-header {
  display: flex;
  align-items: flex-start;
  gap: 15px;
  margin-bottom: 20px;
}

.class-icon {
  width: 50px;
  height: 50px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.class-info {
  flex: 1;
}

.class-name {
  margin: 0 0 5px 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.class-grade {
  margin: 0;
  font-size: 12px;
  color: #909399;
}

.class-actions {
  margin-left: auto;
}

.class-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  padding: 15px 0;
  border-top: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 20px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

.class-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.class-detail {
  padding: 10px 0;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.detail-header h3 {
  margin: 0;
  color: #303133;
}

.class-courses {
  margin-top: 20px;
}

.class-courses h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.course-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .classes-grid {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .class-stats {
    flex-direction: column;
    gap: 10px;
  }
  
  .stat-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    text-align: left;
  }
  
  .stat-number {
    font-size: 16px;
    margin-bottom: 0;
  }
}
</style> 